﻿using RBAC_Application.Repository.Interface;
using RBAC_Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RBAC_Application.Repository.Implement
{
    public class RoleRepository : IRoleRepository
    {
        private readonly ISqlSugarClient _db;

        public RoleRepository(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 根据角色ID获取角色信息
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns>角色对象</returns>
        public Role GetById(long id)
        {
            return _db.Queryable<Role>().First(r => r.Id == id);
        }

        /// <summary>
        /// 获取所有角色信息
        /// </summary>
        /// <returns>角色列表</returns>
        public List<Role> GetAll()
        {
            return _db.Queryable<Role>().ToList();
        }

        /// <summary>
        /// 根据关键字条件获取角色信息
        /// </summary>
        /// <param name="keyword">关键字</param>
        /// <returns>角色列表</returns>
        public List<Role> GetByCondition(string keyword)
        {
            var query = _db.Queryable<Role>();
            
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(r => r.RoleName.Contains(keyword) || r.Description.Contains(keyword));
            }
            
            return query.ToList();
        }

        /// <summary>
        /// 根据用户ID获取其拥有的角色
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>角色列表</returns>
        public List<Role> GetRolesByUserId(long userId)
        {
            return _db.Queryable<Role>()
                .InnerJoin<UserRole>((r, ur) => r.Id == ur.RoleId)
                .Where((r, ur) => ur.UserId == userId)
                .Select((r, ur) => r)
                .ToList();
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="role">角色对象</param>
        public void Add(Role role)
        {
            _db.Insertable(role).ExecuteCommand();
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        /// <param name="role">角色对象</param>
        public void Update(Role role)
        {
            _db.Updateable(role).ExecuteCommand();
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id">角色ID</param>
        public void Delete(long id)
        {
        
            _db.Updateable<Role>().SetColumns(u => u.IsDeleted == true).Where(u => u.Id == id).ExecuteCommand();
        }

        /// <summary>
        /// 判断角色名称是否已存在
        /// </summary>
        /// <param name="roleName">角色名称</param>
        /// <returns>true表示已存在，false表示不存在</returns>
        public bool Exists(string roleName)
        {
            return _db.Queryable<Role>().Any(r => r.RoleName == roleName);
        }
    }
}
